<template>
<div class="ruleConfig">
  <search-block>
    <template slot="button">
      <el-button type="primary" @click="search(true)">查询</el-button>
      <el-button type="primary" @click="addRule">添加规则</el-button>
    </template>
    <el-form inline :model="model" label-width="100px">
      <el-form-item label="名称:">
        <el-input v-model="model.name" clearable></el-input>
      </el-form-item>
      <el-form-item label="是否启用:">
        <el-select v-model="model.status" clearable>
          <el-option label="是" :value="0"></el-option>
          <el-option label="否" :value="1"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </search-block>
  <y-table
    ref="table"
    border
    pagination
    :getDataWay="getDataWay"
    :columns="columns">
    <el-table-column slot="status" label="启用" align="center" header-align="center" width="80">
      <template v-slot="{row}">
        <el-popconfirm
          :title="row.status === '1' ? '是否确认启用该规则？' : '是否确认禁用该规则？'"
          @confirm="() => {
            if(row.status === '1') enable(row)
            else disable(row);
          }"
        >
          <el-switch
            disabled
            slot="reference"
            v-model="row.status"
            active-value="0"
            inactive-value="1"></el-switch>
        </el-popconfirm>
      </template>
    </el-table-column>
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="150">
      <template v-slot="{row}">
        <div class="table-buttons">
          <el-button type="primary" size="mini" @click="editRule(row)">编辑</el-button>
          <el-popconfirm
            title="是否确认删除该规则？"
            @confirm="delRule(row)">
            <el-button slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
        </div>
      </template>
    </el-table-column>
  </y-table>
  <y-form
    v-model="forms.formModel"
    :visible.sync="forms.showForm"
    :title="forms.formTypeTitle[forms.formsType]"
    destroy-on-close
    width="900px"
    force-inner-scroll
    :form-attrs="forms.formAttrs"
    :columns="formColumns"
    @ensure="ensureModel">
    <template slot="rulesJson">
      <rule-config-details v-model="this.forms.formModel.rulesJson"></rule-config-details>
    </template>
  </y-form>
</div>
</template>

<script>
import RuleConfigDetails from "./ruleConfigDetails/ruleConfigDetails";
export default {
  name: "ruleConfig",
  components: {RuleConfigDetails},
  inject: ['getEnum'],
  computed: {
    getDataWay() {
      return {
        dataType: 'url',
        data: this.$api.sem.semRulePage,
        param: this.model
      }
    },
    formColumns(){
      return [
        {
          label: "规则名称",
          prop: "name",
          comp:{
            compType: 'input',
            attrs:{
              maxlength: 30,
              showWordLimit: true
            }
          }
        },{
          label: "规则类型",
          prop: "ruleType",
          comp:{
            compType: 'select',
            options: this.ruleTypeOptions
          }
        },{
          label: "规则说明",
          prop: "introduction",
          comp:{
            compType: 'input',
            attrs:{
              type: 'textarea',
              maxlength: 100,
              showWordLimit: true,
              autosize: {
                minRows: 3
              }
            }
          }
        },{
          label: "规则配置",
          prop: "rulesJson",
          class: 'is-required',
          template: true
        }
      ]
    }
  },
  data(){
    return{
      ruleTypeOptions: this.getEnum('ruleType'),
      model:{
        name: '',
        status: ''
      },
      columns: [
        {
          label: "名称",
          prop: "name",
          minWidth: 100,
        },
        {
          label: "类型",
          prop: "ruleType",
          minWidth: 100,
          formatter: (function(row){
            return this.$$getCommonArrayName(row.ruleType, this.ruleTypeOptions)
          }).bind(this)
        },
        {
          label: "说明",
          prop: "introduction",
          minWidth: 300
        },
        {
          prop: "status",
          template: true
        }
      ],
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加规则',
          'EDIT': '编辑规则'
        },
        formModel:{
          name: '',
          ruleType: '',
          rulesJson: [],
          introduction: ''
        },
        currentForm: null,
        showForm: false,
        formAttrs:{
          labelWidth: '100px',
          rules: {
            name: [{required: true, message: "请输入规则名称", trigger: "blur"}],
            ruleType: [{required: true, message: "请选择规则类型", trigger: "change"}],
            rulesJson: [
              {
                validator: (rule, value, callback) => {
                  if(value.some(item => !item.ruleCode)){
                    callback(new Error("存在未填写完成的规则项，请检查您的配置"));
                  }else if(!value.length){
                    callback(new Error("请配置规则"));
                  }else{
                    callback();
                  }
                },
                trigger: 'change'
              }
            ]
          }
        }
      },
    }
  },
  methods:{
    search(jumpToFirst){
      this.$refs['table'].loadData(this.model, jumpToFirst);
    },
    resetForm(){
      Object.keys(this.forms.formModel).map(key => {
        if(key === 'rulesJson'){
          if(this.forms.currentForm){
            this.forms.formModel[key] = this.forms.currentForm[key] ? JSON.parse(this.forms.currentForm[key]) : [];
          }else{
            this.forms.formModel[key] = [];
          }
        }
        else this.forms.formModel[key] = this.forms.currentForm ? this.forms.currentForm[key] : '';
      })
    },
    addRule(){
      this.forms.formsType = 'ADD';
      this.forms.currentForm = null;
      this.resetForm();
      this.forms.showForm = true;
    },
    editRule(row){
      this.forms.formsType = 'EDIT';
      this.forms.currentForm = row;
      this.resetForm();
      this.forms.showForm = true;
    },
    delRule(row){
      this.$yAxios({
        url: this.$api.sem.removeSemRule,
        data:{
          ids: [row.id]
        }
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.search();
      })
    },
    ensureModel(form){
      let newForm;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
      }else{
        newForm = Object.assign({}, form);
      }
      newForm.rulesJson = JSON.stringify(newForm.rulesJson);
      this.$yAxios({
        url: this.$api.sem.saveSemRule,
        data: newForm
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.search(this.forms.formsType === 'ADD');
      })
    },
    enable(row){
      this.$yAxios({
        url: this.$api.sem.enableSemRule,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: `成功启用规则【${row.name}】`
        });
        this.search()
      });
    },
    disable(row){
      this.$yAxios({
        url: this.$api.sem.disableSemRule,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: `成功禁用规则【${row.name}】`
        });
        this.search()
      });
    },
  }
}
</script>

<style scoped>

</style>